# 错误中断调试函数
err_exit() {
    echo "$1"
    exit "$2"
}

# 行分隔符
line_separator() {
    test -z "$2" || echo -e "\n======================================================================================\n"
    echo -e "$1"
}

# yum 方式安装软件包
yum_install() {
    for package in "$@"
    do
        check_package_exists "$package" centos

        if [ "$?" -eq 0 ]; then
            yum install "$package" -y
        fi
    done
}

# yum 方式卸载软件包
yum_remove() {
    for package in "$@"
    do
        local package_list=$(rpm -qa | egrep "$package")
        if [ x"$package_list" != x ]; then
            for package_name in $package_list
            do
                rpm -ev --nodeps "$package_name"
            done
        else
            line_separator "$package uninstalled,no available packages to remove."
        fi
    done
}

# rpm 文件方式安装软件包
rpm_file_install() {
    local url="$1"
    shift
    for rpm_file in "$@"
    do
        wget "$url"/"$rpm_file" || err_exit "download $rpm_file failed,please check the url is correct." 2
        rpm -ivh "$rpm_file" || err_exit "install $rpm_file failed,please check." 2
        rm "$rpm_file" -rf
    done
}

# 检查软件包是否已安装
check_package_exists() {
    local package="$1"
    if [ x"$2" = xcentos ]; then
        rpm -q "$package" &> /dev/null
    else
        dpkg -s "$package" &> /dev/null
    fi

    local res_a="$?"
    which "$package" &> /dev/null
    local res_b="$?"

    if [ ! "$res_a" -eq 0 -a ! "$res_b" -eq 0 ]; then
        return 0
    else
        line_separator "$package installed,nothing to deal with."
        return 1
    fi
}

# rpm 方式安装软件包
rpm_install() {
    local package="$1"
    local url="$2"
    local rpm_file="$3"
    local package_name="$4"

    check_package_exists "$package" centos

    if [ "$?" -eq 0 ]; then
        wget "$url"/"$rpm_file" || err_exit "download $rpm_file failed,please check the url is correct." 2
        yum install "$rpm_file" -y || err_exit "install $rpm_file failed,please check." 2
        test -z "$package_name" || yum install "$package_name" -y || err_exit "install $package_name failed,please check." 2
        rm "$rpm_file" -rf
        return 0
    else
        return 1
    fi
}

# 从标准输入读取变量
read_from_stdin() {
    while read -p "$1" "$2"
    do
        line_separator "${!2}" | egrep -q "$4"
        if [ ! "$?" -eq 0 -a x"${!2}" != x ]; then
            line_separator "$3"
            continue
        else
            eval "$2"="${!2}"
            break;
        fi
    done
}

# 测试是否中文乱码方法
test_is_chinese() {
    echo "你好,中国"
    echo "你最近怎么样"
    echo "我们去吃大餐吧"
}
